package com.mmall.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.mmall.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class JsonUtil {


    private static ObjectMapper objectMapper = new ObjectMapper();

    static{
        //对象的所有字段全部列入
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);

        //取消默认转换timestamps形式，即12位的时间数字
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        //忽略空bean转换的错误
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        //所有的日期格式都转化为自定义样式yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));

        //忽略在json字符串中存在，但是在java中不存在对应属性的情况，防止错误
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    }

    /**对象转化为字符串
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String objToString(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (IOException e) {
            log.warn("Parse object to String error");
            return null;
        }
    }

    /**Obj转化为格式化后的json字符串
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String objToStringPretty(T obj) {
        if (obj == null) {
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse object to String error",e);
            return null;
        }
    }

    /**String转化为对象
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T stringToObj(String str, Class<T> clazz) {
        if (StringUtils.isEmpty(str) || clazz == null) {
            return null;
        }
        try {
            return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
        } catch (Exception e) {
            log.warn("Parse String to Object error", e);
            return null;
        }
    }

    /**typeReference形式的反序列化，处理例如List<User>类型的对象，
     * 使用方法：List<User> userList2 = JsonUtil.stringToObj(UserListJson, new TypeReference<List<User>>() {});
     * @param str
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T stringToObj(String str, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(str) || typeReference == null) {
            return null;
        }
        try {
            return typeReference.getType().equals(String.class) ? (T) str : (T) objectMapper.readValue(str, typeReference);
        } catch (Exception e) {
            log.warn("Parse String to Object error", e);
            return null;
        }
    }

    /**javaType形式的反序列化
     * @param str
     * @param collectionClass
     * @param elementClasses   ...表示可以传多个参数，用数组形式
     * @param <T>
     * @return
     */
    public static <T> T stringToObj(String str, Class<?> collectionClass,Class<?>... elementClasses) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        JavaType javaType = objectMapper.getTypeFactory().constructParametrizedType(collectionClass,collectionClass, elementClasses);
        try {
            return objectMapper.readValue(str, javaType);
        } catch (Exception e) {
            log.warn("Parse String to Object error", e);
            return null;
        }
    }

    public static void main(String[] args) {
        User u1 = new User();
        u1.setId(1);
        u1.setUsername("xiaozhi");
        u1.setEmail("xiaozhi@mmall.com");
        u1.setCreateTime(new Date());

        User u2 = new User();
        u2.setId(2);
        u2.setUsername("xiaozhi1");
        u2.setEmail("xiaozhi@mmall.com");
        u2.setCreateTime(new Date());

        List<User> users = new ArrayList<>();
        users.add(u1);
        users.add(u2);

        String UserJson = JsonUtil.objToString(u1);

        log.info("UserJson:{}",UserJson);

        String UserJson1 = JsonUtil.objToStringPretty(u1);

        log.info("UserJsonPretty:{}",UserJson1);

        User user = JsonUtil.stringToObj(UserJson, User.class);

        String UserListJson = JsonUtil.objToStringPretty(users);

        log.info("UserListJson:{}",UserListJson);

//        List<User> userList1 = JsonUtil.stringToObj(UserListJson, List.class);

        List<User> userList2 = JsonUtil.stringToObj(UserListJson, new TypeReference<List<User>>() {});

        List<User> userList3 = JsonUtil.stringToObj(UserListJson, List.class, User.class);

                System.out.println("end");
    }
}
